<template>
  <div class="common-layout">
    <!-- 主题切换提示条 -->
    <transition name="el-fade-in">
      <div v-if="isDark" class="theme-notice">
        <el-icon><Moon /></el-icon>
        <span>{{ t('theme.darkModeEnabled') }}</span>
      </div>
    </transition>
    
    <el-container>
      <el-header class="header-wrapper">
        <!-- 左侧Logo -->
        <div class="logo-area">
          <el-icon :size="32" color="#42d392">
            <Monitor />
          </el-icon>
          <span class="logo-text">Electron-Egg</span>
        </div>

        <!-- 右侧：时钟 + 用户信息 -->
        <div class="right-area">
          <!-- 实时时钟（带提示） -->
          <el-tooltip :content="$t('clock.currentTime')" placement="bottom">
            <div class="clock-box">
              <el-icon :size="20" color="#647eff">
                <Clock />
              </el-icon>
              <span class="current-time">{{ fullDateTime }}</span>
            </div>
          </el-tooltip>

          <!-- 常用图标入口：通知 / 主题 / 帮助 -->
          <div class="header-actions">
            <!-- 通知中心：带徽章和开关状态 -->
            <el-tooltip :content="notificationEnabled ? $t('notification.title') : $t('notification.disabled')" placement="bottom">
              <el-badge 
                :value="unreadCount" 
                :hidden="unreadCount === 0 || !notificationEnabled"
                :max="99"
                class="notification-badge"
              >
                <el-icon 
                  class="icon-btn notification-icon" 
                  :class="{ 'is-disabled': !notificationEnabled }"
                  @click="openNotice"
                >
                  <Bell v-if="notificationEnabled" />
                  <BellFilled v-else />
                </el-icon>
              </el-badge>
            </el-tooltip>
            
            <el-tooltip :content="isDark ? $t('theme.switchToLight') : $t('theme.switchToDark')" placement="bottom">
              <el-icon class="icon-btn" @click="toggleTheme">
                <Sunny v-if="isDark" />
                <Moon v-else />
              </el-icon>
            </el-tooltip>
            <el-tooltip :content="$t('help.documentation')" placement="bottom">
              <el-icon class="icon-btn" @click="openHelp"><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>

          <!-- 直接退出按钮（无下拉） -->
          <el-button class="logout-btn" type="danger" plain :loading="loggingOut" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            <span style="margin-left:6px;">{{ loggingOut ? $t('common.loggingOut') : $t('common.logout') }}</span>
          </el-button>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-row class="tac">
            <el-col :span="24">
              <el-menu 
                :active-text-color="menuActiveTextColor" 
                :background-color="menuBackgroundColor" 
                class="el-menu-vertical-demo"
                :default-active="$route.path" 
                :text-color="menuTextColor" 
                @open="handleOpen" 
                @close="handleClose"
                @select="handleSelect">
                <!-- 首页 -->
                <el-menu-item index="home">
                  <el-icon>
                    <Monitor />
                  </el-icon>
                  <span>{{ $t('menu.home') }}</span>
                </el-menu-item>

                <!-- 个人信息 -->
                <el-menu-item index="profile">
                  <el-icon>
                    <User />
                  </el-icon>
                  <span>{{ $t('menu.profile') }}</span>
                </el-menu-item>

                <!-- 系统设置 -->
                <el-menu-item index="settings">
                  <el-icon>
                    <Setting />
                  </el-icon>
                  <span>{{ $t('menu.settings') }}</span>
                </el-menu-item>

                <!-- AI 聊天 -->
                <el-menu-item index="ai-chat">
                  <el-icon>
                    <ChatDotRound />
                  </el-icon>
                  <span>{{ $t('menu.aiChat') }}</span>
                </el-menu-item>

                <!-- 订单管理 -->
                <el-menu-item index="order-manage">
                  <el-icon>
                    <Tickets />
                  </el-icon>
                  <span>{{ $t('menu.orderManagement') }}</span>
                </el-menu-item>

                <!-- 购物车 -->
                <el-menu-item index="cart">
                  <el-icon>
                    <ShoppingTrolley />
                  </el-icon>
                  <span>{{ $t('menu.cart') }}</span>
                </el-menu-item>

                <!-- 象棋游戏 -->
                <el-menu-item index="chess">
                  <el-icon>
                    <Grid />
                  </el-icon>
                  <span>{{ $t('menu.chess') }}</span>
                </el-menu-item>
                
                <!-- 敏感词管理 -->
                <el-menu-item index="sensitive-word">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  <span>{{ $t('menu.sensitiveWord') }}</span>
                </el-menu-item>
              </el-menu>
            </el-col>
          </el-row>
        </el-aside>
        <!-- 内容区：渲染子路由组件 -->
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
    <!-- 现代风格退出弹窗 -->
    <teleport to="body">
      <el-dialog
        v-model="showLogout"
        width="380px"
        :show-close="!loggingOut"
        :close-on-click-modal="!loggingOut"
        align-center
        class="logout-dialog"
      >
        <div class="ld-icon">
          <el-icon><SwitchButton /></el-icon>
        </div>
        <h3 class="ld-title">{{ $t('logout.title') }}</h3>
        <p class="ld-desc">{{ $t('logout.description') }}</p>
        <div class="ld-actions">
          <el-button size="large" @click="showLogout = false" :disabled="loggingOut">{{ $t('logout.cancel') }}</el-button>
          <el-button type="danger" size="large" :loading="loggingOut" @click="confirmLogout">
            {{ loggingOut ? $t('logout.loggingOut') : $t('logout.confirm') }}
          </el-button>
        </div>
      </el-dialog>
    </teleport>

    <!-- 通知抽屉 -->
    <NotificationDrawer v-model="showNotificationDrawer" />
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useUserStore } from '@/stores/user'  // 导入用户Store
import { useThemeStore } from '@/stores/theme'  // 导入主题Store
import { useNotificationStore } from '@/stores/notification'  // 导入通知Store
import { ElMessage } from 'element-plus';
import api from '@/api';
import NotificationDrawer from '@/components/NotificationDrawer.vue';

const router = useRouter();
const { t } = useI18n();
const userStore = useUserStore();
const themeStore = useThemeStore();
const notificationStore = useNotificationStore();

// 使用全局主题状态
const isDark = computed(() => themeStore.isDark)

// 根据主题动态计算菜单背景色
const menuBackgroundColor = computed(() => isDark.value ? '#1f1f1f' : '#545c64')
const menuTextColor = computed(() => '#fff')
const menuActiveTextColor = computed(() => isDark.value ? '#42d392' : '#ffd04b')

const handleOpen = (key, keyPath) => {
  // 菜单打开处理
}

const handleClose = (key, keyPath) => {
  // 菜单关闭处理
}

// 菜单选中事件：点击菜单时跳转路由
const handleSelect = (index) => {
  // 避免重复跳转（当前路由与点击的菜单路由相同时不执行）
  if (index !== router.path) {
    router.push(index);  // 跳转到选中的路由路径
  }
}

// 实时时钟相关
const fullDateTime = ref('');
// 定时器标识
let timer = null;

// 格式化并更新时间
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  fullDateTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

//

// 通知相关
const showNotificationDrawer = ref(false)
const notificationEnabled = computed(() => notificationStore.enabled)
const unreadCount = computed(() => notificationStore.unreadCount)

// 头部快捷入口
const openNotice = () => {
  if (!notificationEnabled.value) {
    ElMessage.warning(t('notification.disabled'))
    return
  }
  showNotificationDrawer.value = true
}
const toggleTheme = () => {
  themeStore.toggleTheme()
  ElMessage.success(isDark.value ? t('settings.themeSwitchedToDark') : t('settings.themeSwitchedToLight'))
}
const openHelp = () => {
  window.open('https://github.com/dromara/electron-egg', '_blank')
}

// 退出登录
const loggingOut = ref(false)
const showLogout = ref(false)
const handleLogout = () => { if (!loggingOut.value) showLogout.value = true }
const confirmLogout = async () => {
  if (loggingOut.value) return
  loggingOut.value = true
  
  try {
    // 1. 显示退出进度提示
    ElMessage({
      message: t('logout.inProgress'),
      type: 'info',
      duration: 0, // 不自动关闭
      customClass: 'logout-progress-message'
    })
    
    // 2. 调用后端退出接口（清除服务端Session/Cookie）
    await Promise.allSettled([
      api.user.logout(),
      import('@/utils/axios').then(({ cancelAllRequests }) => cancelAllRequests())
    ])
    
    // 3. 清除前端状态
    userStore.logout()
    
    // 4. 显示退出成功提示
    ElMessage.closeAll() // 关闭之前的消息
    ElMessage.success(t('logout.success'))
    
    // 5. 延迟跳转，给用户一点反应时间
    setTimeout(() => {
      const BACKEND_URL = import.meta.env.VITE_GO_URL || 'http://localhost:8181'
      window.location.href = `${BACKEND_URL}/`
    }, 1500) // 1.5秒后跳转
    
  } catch (err) {
    console.error('退出异常：', err)
    ElMessage.closeAll()
    ElMessage.error(t('logout.failed'))
    loggingOut.value = false
    showLogout.value = false
  }
}

// 生命周期钩子（组件挂载时启动时钟）
onMounted(() => {
  updateTime(); // 初始化显示时间
  timer = setInterval(updateTime, 1000); // 每秒更新
  notificationStore.initEnabled(); // 初始化通知开关状态
});

// 组件卸载时清除定时器（防止内存泄漏）
onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>
<style scoped src="@/styles/Layout.scss"></style>
